#include "recommendform.h"
#include "qjsonobject.h"
#include "ui_recommendform.h"

#include "recformitem.h"

recommendForm::recommendForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::recommendForm)
    ,row(1)
    ,col(4)
    ,curindex(0)
{
    ui->setupUi(this);
    // recFormitem* item = new recFormitem(this);
    // ui->up->addWidget(item);
}

recommendForm::~recommendForm()
{
    delete ui;
}

void recommendForm::showRandomRow(QJsonArray arr, int row)
{
    if(row == 2)
    {
        this->row = row;
        col = 8;
    }
    else
        ui->widget_6->hide();
    imgs = arr;
    additemOut();
}

void recommendForm::additemOut()
{
    QLayoutItem* item;
    while ((item = ui->up->takeAt(0)) != nullptr) {
        if (recFormitem* widget = qobject_cast<recFormitem*>(item->widget())) {
            delete widget;
        }
        delete item;
    }

    // 清除原本的元素 down
    QLayoutItem* itemdown;
    while ((itemdown = ui->down->takeAt(0)) != nullptr) {
        if (recFormitem* widget = qobject_cast<recFormitem*>(itemdown->widget())) {
            delete widget;
        }
        delete itemdown;
    }

    //临时变量tmp
    int tmp = 0;
    for(int i = curindex * col; i < col + curindex * col; i++)
    {
        //单独设置文本及图片
        recFormitem* item = new recFormitem(this);
        QJsonObject obj = imgs[i].toObject();
        item->setItemImg(obj.value("path").toString());
        item->setItemText(obj.value("text").toString());
        //添加到水平布局
        if (row == 2 && tmp >= col / 2) {
            ui->down->addWidget(item);
        } else {
            ui->up->addWidget(item);
        }
        tmp++;
    }
}

void recommendForm::on_pushButton_clicked()
{
    curindex--;
    if(curindex <= 0)
    {
        curindex = (imgs.count() - 1) / col;
    }
    additemOut();
}


void recommendForm::on_pushButton_2_clicked()
{
    curindex++;
    if(curindex >= (imgs.count() - 1)/col)
    {
        curindex = 0;
    }
    additemOut();
}

